package com.hanliy.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hanliy.dto.Result;
import com.hanliy.entity.PicStorageEntity;
import com.hanliy.service.StorageService;
import com.hanliy.storage.BaseStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;


/**
 * @author hanyulin
 * @apiNote 文件上传相关
 * @date 2021/11/15 10:07
 */
@RestController
@Api(tags = "文件相关")
@RequestMapping(value = "/storage")
public class StorageController {

    @Resource
    private BaseStorageService baseStorageService;

    @Resource
    private StorageService storageService;

    @PostMapping("/upload")
    @ApiOperation(value = "上传")
    public Result<PicStorageEntity> create(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        PicStorageEntity picStorage = baseStorageService.store(file.getInputStream(), file.getSize(),
                file.getContentType(), originalFilename);
        return new Result<PicStorageEntity>().ok(picStorage);
    }

    @DeleteMapping
    @ApiOperation(value = "删除")
    public Result delete (@RequestBody PicStorageEntity picStorageEntity){
        String key = picStorageEntity.getPicKey();
         baseStorageService.delete(key);
         return new Result().ok();
    }

    @GetMapping(value = "/page")
    @ApiOperation(value = "分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "limit", value = "条数", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "sort", value = "排序字段", required = false, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "order", value = "升序或降序", required = false, dataType = "String", paramType = "query"),
    })
    public Result<List<PicStorageEntity>> page( @RequestParam(defaultValue = "1") Integer page,
                        @RequestParam(defaultValue = "10") Integer limit,
                        @RequestParam(defaultValue = "create_time") String sort
    ){
        List<PicStorageEntity> list = storageService.page(new Page(page, limit), sort);
        return new Result<List<PicStorageEntity>>().ok(list);
    }
}

